package com.zzyl.nursing.service.impl;

import java.util.*;

import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.service.IweChatService;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 老人家属Service业务层处理
 *
 * @author xjl
 * @date 2025-10-16*/


@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private IweChatService weChatService;
    @Autowired
    private TokenService tokenService;

    @Override
    public LoginVo login(UserLoginRequestDto dto) {
        //调出微信code,返回Openid
        String openid = weChatService.getOpenid(dto.getCode());
        //根据Openid查询家庭成员
        LambdaQueryWrapper<FamilyMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMember::getOpenId, openid);
        FamilyMember familyMember = this.getOne(queryWrapper);
        //调用接口获取手机号,返回phone
        String phone = weChatService.getPhone(dto.getPhoneCode());
        //如果查不到,直接新增
        if (familyMember == null) {
            familyMember = new FamilyMember();
            familyMember.setPhone(phone);
            familyMember.setName(DEFAULT_NICKNAME_PREFIX.get(new Random().nextInt(DEFAULT_NICKNAME_PREFIX.size())) + phone.substring(7));
            familyMember.setOpenId(openid);
            this.save(familyMember);
        } else {
            if (!familyMember.getPhone().equals(phone)) {
                familyMember.setPhone(phone);
                this.updateById(familyMember);
            }
        }
        Map<String,Object> map =new HashMap<>();
        map.put("id",familyMember.getId());
        LoginVo loginVo = new LoginVo();
        String token = tokenService.createToken(map);
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());


        return loginVo;
    }

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of("生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );
}
